package com.sfc.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by heylear.cai on 2015/12/28.
 */
public class AuthzUtils {
    final static String SESSION_KEY_USER_ID = "SESSION_KEY_USER_ID";

    public static Long getCurrentUserId(){
        if (getSession() == null){
            return 0l;
        }
        Long userId = (Long)getSession().getAttribute(SESSION_KEY_USER_ID);
        return userId == null ? 0l : userId;
    }

    public static void setCurrentUserId(Long userId){
        if (getSession() == null){
            return;
        }
        getSession().setAttribute(SESSION_KEY_USER_ID, userId);
    }

    protected static HttpSession getSession(){
        try {
            ServletRequestAttributes  requestAttributes = (ServletRequestAttributes )RequestContextHolder.currentRequestAttributes();
            return requestAttributes.getRequest().getSession();
        } catch (Exception e) {
            return null;
        }
    }
}
